package com.qiqidream.admin.security.login;

import com.alibaba.fastjson.JSON;
import com.qiqidream.admin.common.response.ResponseCode;
import com.qiqidream.admin.common.response.ResponseResult;
import com.qiqidream.admin.common.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 认证失败处理 - 前后端分离情况下返回json数据格式
 * @author QiQiDream
 * @since 2019/11/18 9:58
 */
@Slf4j
@Component
public class AdminAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse response, AuthenticationException e) {
        ResponseResult result;
        if (e instanceof UsernameNotFoundException || e instanceof BadCredentialsException) {
            result = ResponseResult.failed(ResponseCode.USER_UNAUTHORIZED);
        } else if (e instanceof LockedException) {
            result = ResponseResult.failed("账户被锁定，请联系管理员!");
        } else if (e instanceof CredentialsExpiredException) {
            result = ResponseResult.failed("证书过期，请联系管理员!");
        } else if (e instanceof AccountExpiredException) {
            result = ResponseResult.failed("账户过期，请联系管理员!");
        } else if (e instanceof DisabledException) {
            result = ResponseResult.failed("账户被禁用，请联系管理员!");
        } else {
            result = ResponseResult.failed(e.getMessage());
        }
        ResponseUtil.out(response, JSON.toJSONString(result));
    }

}
